import React from "react";
import { Flex, WingBlank, WhiteSpace, Toast } from "antd-mobile";

import { Link } from "react-router-dom";

import { API,setToken} from "../../utils";

import { withFormik, Form, Field, ErrorMessage } from "formik";

import * as Yup from "yup";

import NavHeader from "../../components/NavHeader";

import styles from "./index.module.css";

// 验证规则：
const REG_UNAME = /^[a-zA-Z_\d]{5,8}$/;
const REG_PWD = /^[a-zA-Z_\d]{5,12}$/;

let Login = () => {
  // const { values, handleChange, handleSubmit } = props;
  return (
    <div className={styles.root}>
      {/* 顶部导航 */}
      <NavHeader className={styles.navHeader}>账号登录</NavHeader>
      <WhiteSpace size="xl" />

      {/* 登录表单 */}
      <WingBlank>
        <Form>
          <div className={styles.formItem}>
            <Field
              className={styles.input}
              name="username"
              placeholder="请输入账号"
            />
          </div>
          {/* 长度为5到8位，只能出现数字、字母、下划线 */}
          {/* <div className={styles.error}>账号为必填项</div> */}
          <ErrorMessage
            component="div"
            className={styles.error}
            name="username"
          />
          <div className={styles.formItem}>
            <Field
              className={styles.input}
              name="password"
              type="password"
              placeholder="请输入密码"
            />
          </div>
          {/* 长度为5到12位，只能出现数字、字母、下划线 */}
          {/* <div className={styles.error}>账号为必填项</div> */}
          <ErrorMessage
            component="div"
            className={styles.error}
            name="password"
          />
          <div className={styles.formSubmit}>
            <button className={styles.submit} type="submit">
              登 录
            </button>
          </div>
        </Form>
        <Flex className={styles.backHome}>
          <Flex.Item>
            <Link to="/registe">还没有账号，去注册~</Link>
          </Flex.Item>
        </Flex>
      </WingBlank>
    </div>
  );
};

Login = withFormik({
  // 该配置项用来为表单组件提供状态（ 可以代替组件自己的 state ）
  mapPropsToValues: () => ({
    username: "",
    password: ""
  }),

  // 处理表单提交
  handleSubmit: async (values, { props }) => {
    const { username, password } = values;

    const res = await API.post("/user/login", {
      username,
      password
    });
    // console.log(res);
    const { status, body, description } = res.data;

    if (status === 200) {
      setToken(body.token)
      const {state} = props.location
      if(!state){
        props.history.go(-1);
      }else{
        props.history.replace(state.from.pathname)
      }
    } else if (status === 400) {
      // 登陆失败
      Toast.info(description, 2);
    }
  },

  // 处理表当校验
  validationSchema: Yup.object().shape({
    username: Yup.string()
      .required("账号为必填项")
      .matches(REG_UNAME, "长度为5到8位，只能出现数字、字母、下划线"),
    password: Yup.string()
      .required("密码为必填项")
      .matches(REG_PWD, "长度为5到12位，只能出现数字、字母、下划线")
  })
})(Login);

export default Login;
